package dbexp.filter;

import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Michał Skrzyński
 * @email michal_skrzynski@o2.pl
 */
public class GzipFilter implements Filter {

	private ServletContext context;
	private FilterConfig config;

	public void init(FilterConfig config) throws ServletException {
		this.setConfig(config);
		setContext(config.getServletContext());
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain lancuch) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		String enabled_coding = request.getHeader("Accept-Encoding");
		if (enabled_coding.indexOf("gzip") > -1) {
			GzipResponseWrapper packResp = new GzipResponseWrapper(response);
			packResp.setHeader("Content-Encoding", "gzip");

			lancuch.doFilter(request, packResp);

			GZIPOutputStream gzos = packResp.getGZIPOutputStream();
			gzos.flush();
		}
	}

	public void destroy() {
		setContext(null);
		setConfig(null);
	}

	public void setContext(ServletContext context) {
		this.context = context;
	}

	public ServletContext getContext() {
		return context;
	}

	public void setConfig(FilterConfig config) {
		this.config = config;
	}

	public FilterConfig getConfig() {
		return config;
	}
}
